package cn.ywang.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 监听器
 *
 * @author: BeatificWang
 * @date: 2018/12/22 17:04
 */
public class ListenerConsumer {
	public static void main(String[] args) {
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		Connection connection = null;
		try {
			// 创建连接
			connection = factory.createConnection();
			connection.start();
			Session session = connection.createSession(Boolean.TRUE, Session.CLIENT_ACKNOWLEDGE);
			// 目的地
			Destination destination = session.createQueue("myQueue");
			// 消息生产者
			MessageConsumer consumer = session.createConsumer(destination);
			MessageListener listener = new MessageListener() {
				@Override
				public void onMessage(Message message) {
					try {
						// 接收消息，若此时没有消息，则阻塞，直到收到消息
						System.out.println(((TextMessage) message).getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			};
			while (true) {
				// listener和consumer.receive()是互斥的 只能存在其一
				consumer.setMessageListener(listener);
				session.commit();
			}
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
